using System;
using System.Collections.Generic;
using System.Text;

namespace DigitalTrainSuite.Canvas
{
	class Grid
	{
		private GridSquare[][] grid;
		private int snapRes;
		private int sizeX;
		private int sizeY;

	#region public properties

		public GridSquare this[int x, int y]
		{
			get
			{
				return this.grid[(int)Math.Floor((double)(x / this.snapRes))][(int)Math.Floor((double)(y / this.snapRes))];
			}

			set
			{
				this.grid[(int)Math.Floor((double)(x / this.snapRes))][(int)Math.Floor((double)(y / this.snapRes))] = value;
			}
		}

		public GridSquare this[double x, double y]
		{
			get
			{
				if (x <= 0 || y <= 0) return null;
				return this.grid[(int)Math.Floor(x / this.snapRes)][(int)Math.Floor(y / this.snapRes)];
			}

			set
			{
				this.grid[(int)Math.Floor(x / this.snapRes)][(int)Math.Floor(y / this.snapRes)] = value;
			}
		}

		public double SnapRes
		{
			get { return this.snapRes; }
		}

		#endregion

	#region public methods

		public Grid(int sizeX, int sizeY, int snapRes)
		{
			this.sizeX = sizeX;
			this.sizeY = sizeY;
			this.snapRes = snapRes;

			this.grid = new GridSquare[sizeX][];
			for (int i = 0; i < sizeX; i++)
			{
				this.grid[i] = new GridSquare[sizeY];
			}
		}

		public void addTrack(DataSetLayout.TrackRow track)
		{
			List<DoublePoint> points = EndPoint.findEndPoints(track);

			List<DoublePoint> midPoints = EndPoint.findMidPoints(track);

			foreach (DoublePoint point in midPoints)
			{
				if (point.X > 0 && point.Y > 0)
				{
					this[point.X, point.Y] = new GridSquare(track.id, point, false);
				}
			}

			foreach (DoublePoint point in points)
			{
				if (point.X > 0 && point.Y > 0)
				{
					this[point.X, point.Y] = new GridSquare(track.id, point, true);
				}
			}
		}

		public DoublePoint snapTo(double x, double y)
		{
			if (this[x, y] != null && this[x, y].EndPoint)
			{
				return this[x, y].SnapPoint;
			}
			else
			{
				for (int i = -1; i <= 1; i++)
				{
					for (int j = -1; j <= 1; j++)
					{
						if (this[x + i, y + j] != null && this[x + i, y + j].EndPoint)
						{
							return this[x + i, y + j].SnapPoint;
						}
					}
				}
				return null;
			}
		}

		public void clearGrid()
		{
			for (int i = 0; i < this.sizeX; i++)
			{
				for (int j = 0; j < this.sizeY; j++)
				{
					this.grid[i][j] = null;
				}
			}
		}

		public int moveTrack(double X, double Y)
		{
			if (this[X, Y] != null)
			{

				return this[X, Y].TrackId;
			}
			else
			{
				return -1 ;
			}
		}

		#endregion

	#region private methods

		

	#endregion
	}
}
